package featuresdemo;

import org.apache.commons.lang3.builder.ToStringBuilder;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by pc on 2015/4/29.
 */
public class ImmutableClassBadDemo {
    public static void main(String args[]){
        Calendar ca = Calendar.getInstance();

        Date plannedDate = ca.getTime();
        BrokenPerson bp = new BrokenPerson("san", "zhang", plannedDate);
        ImmutablePerson ip = new ImmutablePerson("san", "zhang", plannedDate);

        System.out.println("now is " + plannedDate);

        System.out.println("bp.date: "  + bp.getDOB());
        System.out.println("ip.date: "  + ip.getDOB());

        System.out.println(bp);
        System.out.println(ip);
        ca.add(Calendar.MONTH, 1);
        plannedDate = ca.getTime();

        System.out.println("new now is " + plannedDate);

        System.out.println("bp.date: "  + bp.getDOB());
        System.out.println("ip.date: " + ip.getDOB());

        System.out.println(bp);
        System.out.println(ip);

//        BrokenPerson bp1 = new BrokenPerson("san", "zhang", plannedDate);
//        ImmutablePerson ip1 = new ImmutablePerson("san", "zhang", plannedDate);

//        System.out.println("bp == bp1? " + (bp == bp1));
//        System.out.println("ip == ip1? " + (ip == ip1));

    }
}


final class BrokenPerson {
    private String firstName;
    private String lastName;
    private Date dob;

    public BrokenPerson(String firstName, String lastName, Date dob) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;     //error
    }

    public String getFirstName() {
        return this.firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public Date getDOB() {
        return this.dob;    //error
    }

    public String toString(){
        return ToStringBuilder.reflectionToString(this);
    }
}


final class ImmutablePerson {
    private String firstName;
    private String lastName;
    private Date dob;

    public ImmutablePerson(String firstName, String lastName, Date dob) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = new Date(dob.getTime());
    }

    public String getFirstName() {
        return this.firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public Date getDOB() {
        return  new Date(dob.getTime());
    }

    public String toString(){
        return ToStringBuilder.reflectionToString(this);
    }
}
